package com.pansoft.openplanet.activity;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.efounder.chat.manager.PictureAndCropManager;
import com.efounder.chat.utils.PansoftCloudUtil;
import com.efounder.util.FileDeleteUtil;
import com.efounder.utils.ResStringUtil;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.bean.WalletBean;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.util.PrivateKeyUtils;
import com.pansoft.openplanet.widget.CommonEditextAlertDialog;
import com.pansoft.openplanet.widget.ExportPrivateKeyDialog;
import com.pansoft.openplanet.widget.PassWordAlertDialog;
import com.pansoft.openplanet.widget.SelectAvatarDialog;
import com.utilcode.util.ToastUtils;

import java.io.File;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import static com.efounder.chat.manager.PictureAndCropManager.PHOTO_REQUEST_CUT;
import static com.efounder.chat.manager.PictureAndCropManager.PHOTO_REQUEST_GALLERY;
import static com.efounder.chat.manager.PictureAndCropManager.PHOTO_REQUEST_TAKEPHOTO;
import static com.efounder.frame.utils.NetStateBroadcastReceiver.isNetActive;

/**
 * Created by will on 18-3-27.
 */
@Deprecated
public class AccountDetailActivity extends TCBaseActivity implements View.OnClickListener {

    private ImageView ivAvatar, ivCopy, ivSell, ivBuy, ivTrendMore, ivDelete;
    private TextView tvAccountName, tvWalletAddress, tvAssetsValue,
            tvSell, tvBuy, tvDealTrend;
    private AccountDao accountDao;
    private Account account;
    private WalletBean walletBean;
    private PictureAndCropManager pictureAndCropManager;//拍照裁剪
    private SelectAvatarDialog selectAvatarDialog;
    private String pictureUrlPath = "";//头像在网络上的位置


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.talk_chain_activity_account_detail);
        initView();
        initData();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dispose();
    }

    private void initData() {

        pictureAndCropManager = new PictureAndCropManager(this);
        selectAvatarDialog = new SelectAvatarDialog(this, pictureAndCropManager);
        walletBean = (WalletBean) getIntent().getSerializableExtra("bean");
        accountDao = new AccountDao(this);
        String address = walletBean.getAddress();
        if (address.length() > 20) {
            address = address.replace(address.substring(6, address.length() - 4), "****");
            tvWalletAddress.setText(address);
        }
        account = accountDao.getAccount(walletBean.getAddress());
        if (account == null) {
            account = new Account();
            account.setAddress(walletBean.getAddress());
        }
        tvAccountName.setText(account.getAcccountName());
        showUserAvatar(account.getAccountAvatar());
        tvAssetsValue.setText(walletBean.getBalance());
    }

    private void initView() {
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(ResStringUtil.getString(R.string.open_planet_detail));
        ImageView ivBack = (ImageView) findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        tvAccountName = (TextView) findViewById(R.id.tv_account_name);
        tvAccountName.setOnClickListener(this);
        tvWalletAddress = (TextView) findViewById(R.id.tv_wallet_address);
        tvAssetsValue = (TextView) findViewById(R.id.tv_assets_value);

        tvSell = (TextView) findViewById(R.id.tv_sell);
        tvSell.setOnClickListener(this);
        tvBuy = (TextView) findViewById(R.id.tv_buy);
        tvBuy.setOnClickListener(this);
        tvDealTrend = (TextView) findViewById(R.id.tv_deal_trend);
        tvDealTrend.setOnClickListener(this);
        ivCopy = (ImageView) findViewById(R.id.iv_copy);
        ivCopy.setOnClickListener(this);
        ivDelete = (ImageView) findViewById(R.id.iv_delete);
        ivDelete.setOnClickListener(this);
        ivSell = (ImageView) findViewById(R.id.iv_sell);
        ivSell.setOnClickListener(this);
        ivBuy = (ImageView) findViewById(R.id.iv_buy);
        ivBuy.setOnClickListener(this);
        ivTrendMore = (ImageView) findViewById(R.id.iv_more);
        ivTrendMore.setOnClickListener(this);
        ivAvatar = (ImageView) findViewById(R.id.iv_wallet);
        ivAvatar.setOnClickListener(this);
        TextView tv_backup = (TextView) findViewById(R.id.tv_backup);
        tv_backup.setOnClickListener(this);

//        ConstraintLayout constraintLayout =(ConstraintLayout)findViewById(R.id.constop);
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            constraintLayout.setOutlineProvider(new ViewOutlineProvider() {
//                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
//                @Override
//                public void getOutline(View view, Outline outline) {
//                    outline.setRect(0,0,
//                            view.getWidth(),view.getHeight());
//                }
//            });
//            constraintLayout.setClipToOutline(true);
//        }

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.iv_delete) {
            //删除账号
            new AlertDialog.Builder(AccountDetailActivity.this).setTitle(R.string.common_text_hint).setMessage(ResStringUtil.getString(R.string.open_planet_remove_account_confirm))
                    .setPositiveButton(ResStringUtil.getString(R.string.common_text_confirm), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    FileDeleteUtil.delete(new File(walletBean.getFilePath()));
                    accountDao.delete(walletBean.getAddress());
                    finish();
                }
            }).setNegativeButton(R.string.common_text_cancel, null).show();
        } else if (id == R.id.iv_copy) {
            //复制账号
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            // 将文本内容放到系统剪贴板里。
            cm.setText(walletBean.getAddress());
            ToastUtils.showShort(R.string.open_planet_copy_account_to_clip_board);
        } else if (id == R.id.tv_account_name) {
            //修改账户名
            CommonEditextAlertDialog commonEditextAlertDialog =
                    new CommonEditextAlertDialog(AccountDetailActivity.this, new CommonEditextAlertDialog.OnEnterClick() {
                        @Override
                        public void passVerifySuccess(String name) {
                            account.setAcccountName(name);
                            tvAccountName.setText(name);
                            accountDao.insertOrReplace(account);
                            ToastUtils.showShort(R.string.open_planet_change_success);
                        }
                    });
            commonEditextAlertDialog.setTitleTextView(ResStringUtil.getString(R.string.open_planet_change_account_name));
            commonEditextAlertDialog.setContent(account.getAcccountName());
            commonEditextAlertDialog.setEditHint(ResStringUtil.getString(R.string.open_planet_input_new_account_name));
            commonEditextAlertDialog.show();

        } else if (id == R.id.iv_wallet) {
            //修改头像
            selectAvatarDialog.show();
        } else if (id == R.id.iv_sell || id == R.id.tv_sell) {
            //卖米  转账界面
            Intent intent = new Intent(AccountDetailActivity.this, TransferActivity.class);
            intent.putExtra("myaddress", walletBean.getAddress());
            intent.putExtra("balance", walletBean.getBalance());
            intent.putExtra("filePath", walletBean.getFilePath());
            startActivity(intent);
        } else if (id == R.id.tv_buy | id == R.id.iv_buy) {
            //买米
        } else if (id == R.id.tv_deal_trend || id == R.id.iv_more) {
            //行情
        } else if (id == R.id.tv_backup) {
            //备份
            PassWordAlertDialog dialog = new PassWordAlertDialog(AccountDetailActivity.this, new PassWordAlertDialog.OnEnterClick() {
                @Override
                public void passVerifySuccess(String passWord) {
                    coverPrimaryKey();
                }
            });
            dialog.show();
        }
    }

    //备份私钥
    private void coverPrimaryKey() {
        Disposable disposable = Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                String key = PrivateKeyUtils.exportPrivateKey(walletBean.getFilePath(), "");
                emitter.onNext(key);
                emitter.onComplete();
            }
        }).subscribeOn(Schedulers.io()).doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                showLoading(ResStringUtil.getString(R.string.open_planet_generating_private_key));
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                dismissLoading();
                ExportPrivateKeyDialog dialog = new ExportPrivateKeyDialog(AccountDetailActivity.this);
                dialog.setMessage(s);
                dialog.show();
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                dismissLoading();
                ToastUtils.showShort(R.string.open_planet_get_private_key_fail);
            }
        });

        addDisposable(disposable);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PHOTO_REQUEST_TAKEPHOTO:
                    pictureAndCropManager.startPhotoZoom(Uri.fromFile(
                            new File(pictureAndCropManager.getPicturePath())), 300);

                    break;

                case PHOTO_REQUEST_GALLERY:
                    if (data != null)
                        pictureAndCropManager.startPhotoZoom(data.getData(), 300);
                    break;

                case PHOTO_REQUEST_CUT:
//                    Log.i("剪裁后头像文件路径：", pictureAndCropManager.getPicturePath());
                    if (!isNetActive()) {
                        ToastUtils.showShort(R.string.common_text_network_error_please_again);
                        return;
                    }
                    showLoading(ResStringUtil.getString(R.string.common_text_uploading_avatar));

                    try {
                        PansoftCloudUtil.getCloudRes(pictureAndCropManager.getPicturePath(), new PansoftCloudUtil.UpLoadListener() {
                            @Override
                            public void getHttpUrl(Boolean isSuccess, String url) {
                                dismissLoading();
                                if (isSuccess) {
//                                    Log.i("MyUserInfoActivity", "---头像在云盘服务器上的路径:" + url);
                                    pictureUrlPath = url;
                                    pictureUrlPath.trim();
                                    account.setAccountAvatar(pictureUrlPath);
                                    accountDao.insertOrReplace(account);

                                    ToastUtils.showShort(R.string.common_text_upload_success);
                                    showUserAvatar(pictureUrlPath);
                                } else {
                                    ToastUtils.showShort(R.string.common_text_upload_fail_again);
                                }
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    break;
                default:
                    break;

            }

            super.onActivityResult(requestCode, resultCode, data);

        }
    }

    /**
     * 显示用户头像
     */
    private void showUserAvatar(String url) {
        RequestOptions options = new RequestOptions()
                .circleCrop().error(R.drawable.contact_detail_default_avatar).placeholder(R.drawable.contact_detail_default_avatar)
                .diskCacheStrategy(DiskCacheStrategy.ALL);
        Glide.with(this)
                .load(url)
                .apply(options)
                .into(ivAvatar);
    }
}
